package com.syt.cellphone.information.ui.main.setting

import android.os.Bundle
import android.view.View
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.syt.cellphone.information.App
import com.syt.cellphone.information.R
import com.syt.cellphone.information.base.VMBaseFragment
import com.syt.cellphone.information.constant.PreferKey
import com.syt.cellphone.information.lib.theme.ATH
import com.syt.cellphone.information.utils.getViewModel
import kotlinx.android.synthetic.main.view_title_bar.*
import org.jetbrains.anko.toast

/**
 *  @author: syt
 *  创建时间: 2020/8/24 17:19
 *  @功能
 *  @version v1.0
 */
class SettingFragment : VMBaseFragment<SettingViewModel>(R.layout.fragment_setting) {

    override val viewModel: SettingViewModel
        get() = getViewModel(SettingViewModel::class.java)

    override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
        if (toolbar != null) {
            setSupportToolbar(toolbar)
        }
        val fragmentTag = "prefFragment"
        var preferenceFragment = childFragmentManager.findFragmentByTag(fragmentTag)
        if (preferenceFragment == null) {
            preferenceFragment = PreferenceFragment()
        }
        childFragmentManager.beginTransaction()
            .replace(R.id.pre_fragment, preferenceFragment, fragmentTag).commit()
    }

    class PreferenceFragment: PreferenceFragmentCompat() {

        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            // 扩展给定的XML资源并将首选项层次结构添加到当前*首选项层次结构。
            addPreferencesFromResource(R.xml.pref_setting)
            findPreference<ListPreference>(PreferKey.themeMode)?.let {
                // 改变选项监听
                it.setOnPreferenceChangeListener { _, _ ->
                    view?.post { App.INSTANCE.applyDayNight() }
                    true
                }
            }
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            ATH.applyEdgeEffectColor(listView)
        }

        override fun onPreferenceTreeClick(preference: Preference?): Boolean {
            when (preference?.key) {
                "theme_setting" -> context?.toast("打开主题设置活动")
            }
            return super.onPreferenceTreeClick(preference)
        }
    }

}